package com.liao.member.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.liao.member.constant.WxConstants;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: ljt
 * @Description: 小程序登录工具类
 * @DateTime: 2025/3/14 下午5:10
 **/
@Slf4j
public class WechatUtil {

    /**
     * 根据微信code获取openId和sessionKey
     *
     * @param code
     * @return
     */
    public static JSONObject getSessionKeyOrOpenId(String code) {
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> requestUrlParam = new HashMap<>();
        // https://mp.weixin.qq.com/wxopen/devprofile?action=get_profile&token=164113089&lang=zh_CN
        //小程序appId
        requestUrlParam.put("appid", WxConstants.APPID);
        //小程序secret
        requestUrlParam.put("secret", WxConstants.SECRET);
        //小程序端返回的code
        requestUrlParam.put("js_code", code);
        //默认参数
        requestUrlParam.put("grant_type", "authorization_code");
        //发送post请求读取调用微信接口获取openid用户唯一标识
        JSONObject jsonObject = JSON.parseObject(HttpClientUtil.doPost(requestUrl, requestUrlParam));
        return jsonObject;
    }


    /**
     * 获取手机号（手机号的code和获取openid的是不一样的）
     *
     * @param code
     * @return
     */
    public static String getPhone(String code) {

        //1.请求获取access_token
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token";
        Map<String, String> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid", WxConstants.APPID);
        requestUrlParam.put("secret", WxConstants.SECRET);
        requestUrlParam.put("grant_type", "client_credential");

        JSONObject jsonObject = JSON.parseObject(HttpClientUtil.doPost(requestUrl, requestUrlParam));
        String access_token = (String) jsonObject.get("access_token");

        log.info("access_token:{}", access_token);


//        2.使用access_token和code获取手机号

        String phoneUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?=";
        Map<String, String> params = new LinkedHashMap<>();
        params.put("access_token", access_token);
        String body = "{\"code\":\"" + code + "\"}";


        JSONObject PhoneJsonObj = JSON.parseObject(HttpClientUtil.doPost(phoneUrl, params, body));
        if (PhoneJsonObj.get("phone_info") == null) {
            throw new RuntimeException("获取手机号失败");
        }
        
        log.info(String.valueOf(PhoneJsonObj));
        JSONObject phoneInfo = (JSONObject) PhoneJsonObj.get("phone_info");
        String phoneNumber = (String) phoneInfo.get("phoneNumber");

        return phoneNumber;

    }
}
